﻿/**
* ...
* @author Default
* @version 0.1
*/

package bdz.common.display.core {
	
	import fl.data.DataProvider;
	import fl.events.DataChangeEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.*;
	
	public class AbstractDisplayList extends Sprite {
		
		protected var _dp:DataProvider;
		protected var _renderer:String;
		
		function AbstractDisplayList(access:AbstractRestriction = null){
			if(access == null){
				throw new Error("NullPointerException on Abstract Class :: " + getQualifiedClassName(AbstractDisplayList));
			}
			addEventListener(Event.ADDED_TO_STAGE, initializeComponent);
			addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
		}
		protected function cleanUp(evt:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE, initializeComponent);
			removeEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
			try{
				_dp.removeEventListener(DataChangeEvent.DATA_CHANGE, onDataChanged);
				_dp.removeEventListener(DataChangeEvent.PRE_DATA_CHANGE, onBeforeDataChange);
			}catch(e:Error){
				
			}
		}
		protected function initializeComponent(evt:Event):void{
			
		}
		protected static function getAccess():AbstractRestriction {
			return new AbstractRestriction();
		}
		private function onDataChanged(evt:DataChangeEvent):void{
			refreshView(evt);
		}
		private function onBeforeDataChange(evt:DataChangeEvent):void{
			dataAboutToChange(evt);
		}
		protected function dataAboutToChange(evt:DataChangeEvent):void{
			//optional
			//throw new Error("Virtual function: dataAboutToChange() please implement");
		}
		protected function refreshView(evt:DataChangeEvent):void{
			throw new Error("Virtual function: refreshView() please implement");
		}
		private function setUpDPEvents():void{
			//try to remove previous registration first to avoid multiple dispatching
			try{
				_dp.removeEventListener(DataChangeEvent.DATA_CHANGE, onDataChanged);
				_dp.removeEventListener(DataChangeEvent.PRE_DATA_CHANGE, onBeforeDataChange);
			}catch(e:Error){
				
			}
			_dp.addEventListener(DataChangeEvent.DATA_CHANGE, onDataChanged);
			_dp.addEventListener(DataChangeEvent.PRE_DATA_CHANGE, onBeforeDataChange);
		}
		protected function renderElements():void{
			throw new Error("Virtual function: renderElements() please implement");
		}
		public function set dataProvider(dp:*):void {
			try{
				_dp = new DataProvider(dp);
			}catch (e:Error) {
				throw new Error("Invalid dataProvider type");
			}
			setUpDPEvents();
			renderElements();
		}
		public function get dataProvider():DataProvider{
			return _dp;
		}
		public function set renderer(s:String):void{
			_renderer = s;
		}
		public function get renderer():String{
			return _renderer;
		}
	}
	
	
}
class AbstractRestriction {}